package com.framework;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// 缓存管理器
class CacheManager {
    private final Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService cleanupScheduler =
            Executors.newScheduledThreadPool(1);

    public CacheManager() {
        // 每5分钟清理过期缓存
        cleanupScheduler.scheduleAtFixedRate(this::cleanup, 5, 5, TimeUnit.MINUTES);
    }

    public <R> void put(String key, ComponentOutput<R> value, int ttlSeconds) {
        cache.put(key, new CacheEntry(value, System.currentTimeMillis() + ttlSeconds * 1000));
    }

    @SuppressWarnings("unchecked")
    public <R> ComponentOutput<R> get(String key) {
        CacheEntry entry = cache.get(key);
        if (entry != null && entry.isValid()) {
            return (ComponentOutput<R>) entry.getValue();
        }
        return null;
    }

    private void cleanup() {
        long now = System.currentTimeMillis();
        cache.values().removeIf(entry -> !entry.isValid(now));
    }

    static class CacheEntry {
        private final Object value;
        private final long expiry;

        CacheEntry(Object value, long expiry) {
            this.value = value;
            this.expiry = expiry;
        }

        public Object getValue() {
            return value;
        }

        public boolean isValid() {
            return isValid(System.currentTimeMillis());
        }

        public boolean isValid(long timestamp) {
            return expiry > timestamp;
        }
    }
}